#pragma once
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <assert.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <arpa/inet.h>
#include <string>
#include <functional>
#include "global.h"
#include "codec.h"
#include "Buffer.h"
#include "SafeQueue.h"
class TcpConHandler;
typedef std::function<void(TcpConHandler*, const char* szByte, int len)> MsgCallBack;
typedef std::function<void()> ReadCallBack;

const size_t kBufferSize = 1024;
class TcpConHandler : public reactor::EventHandler
{
public:

	TcpConHandler(reactor::handle_t handle);			
	virtual reactor::handle_t GetHandle() const
	{
		return _handle;
	}
	virtual void HandleWrite();
	virtual void HandleRead();	
	virtual void WriteOutStream(const char* szByte, int len){ _outbuf.append(szByte, len); }
	virtual void HandleError()
	{
		fprintf(stderr, "client %d closed\n", _handle);
		close(_handle);
		_handle = -1;
		g_reactor.RemoveHandler(this);
		if (_codec)
			delete _codec;						
		delete this;
	}	
	void Close(){ HandleError();}
	void OnMsgCall(CodecBase* codec, const MsgCallBack& cb);
	void OnRead(const ReadCallBack& cb){ _readCb = cb; }		
private:	
	ssize_t _DySend();
	ssize_t _DyRev();
private:

	reactor::handle_t _handle;	
	char g_read_buffer[kBufferSize];
	char g_write_buffer[kBufferSize];
	Buffer _inbuf;	
	Buffer _outbuf;
	MsgCallBack _msgCallBack;
	ReadCallBack _readCb;	
	CodecBase* _codec=nullptr;
	SafeQueue<std::string> m_msgQueue;
};
